"ui";
importClass(android.view.View);
var scriptName = '随便刷'
var version = '1.0.0'
var themeColor = '#4EBFDD'
var scriptTitle = scriptName+' v'+version
var APPVersion = '随便刷视频 1.0.0'


var ScriptUIAllStr = ScriptUI.toString()
var ScriptUIStr = ScriptUIAllStr.slice(ScriptUIAllStr.indexOf('{'),ScriptUIAllStr.lastIndexOf('}')).slice(1,-2).replace(/项目标题/g,scriptTitle).replace(/#4EBFDD/g,themeColor)
configIDArr = ScriptUIStr.match(/ id( )?=( )?["|'].*?["|']/g).map(item => item.replace(/ id( )?=( )?["|']|"|'/g,''))
ui.statusBarColor(themeColor);
ui.layout(ScriptUIStr);

function ScriptUI(){
    <vertical>
        <appbar>
            <toolbar bg="#4EBFDD" layout_height="70" margin="-2" id="toolbar" title="项目标题" />
        </appbar>
        <ScrollView>
            <vertical marginTop="5">
                <card w="*" h="auto" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                    <vertical padding="18 8" h="auto">
                        <linear>
                            <Switch margin="12 0" layout_weight="1"  id="autoService"   text="无障碍服务"   textSize="15sp" checked="{{auto.service != null}}" />
                            <Switch margin="12 0" layout_weight="1"  id="floatyService" text="悬浮窗权限"   textSize="15sp" checked="false" />
                        </linear>
                    </vertical>
                    <View bg="#4EBFDD" h="*" w="5" />
                </card>
                <card w="*" h="auto" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                    <vertical padding="18 8" marginBottom="2" h="auto">
                        <text text="[设置]" color="#FFA500"  textStyle="bold" textSize="15sp"/>
                        
                        <horizontal>
                            <text text="划动延时(毫秒):"  textStyle="bold" textSize="15sp"/>
                            <input id="sweep_min" text="2000" color="#666666" w="80"/>
                            <text text=" - "  textStyle="bold" textSize="15sp"/>
                            <input id="sweep_max" text="6000" color="#666666" w="80"/>
                        </horizontal>
                    </vertical>
                    <View bg="#4EBFDD" h="*" w="5" />
                </card>
            
                <card w="*" h="auto" margin="10 5" cardCornerRadius="2dp" cardElevation="1dp" gravity="center_vertical">
                    <button id="startScript" h="auto" text="开始运行" textSize="17"  textStyle="bold" color="#ffffff" bg="#4EBFDD" foreground="?selectableItemBackground" layout_gravity="bottom" />
                    <View bg="#4EBFDD" h="*" w="5" />
                </card>
            </vertical>
        </ScrollView>
    </vertical>
}

auto.waitFor();
var Bezier = function () {

    this.name = "Bezier Factory"

    this.oneBezier = function (t, p1, p2) {
        const [x1, y1] = p1;
        const [x2, y2] = p2;
        let x = x1 + (x2 - x1) * t;
        let y = y1 + (y2 - y1) * t;
        return [x, y];
    }

    this.twoBezier = function (t, p1, cp, p2) {
        const [x1, y1] = p1;
        const [cx, cy] = cp;
        const [x2, y2] = p2;
        let x = (1 - t) * (1 - t) * x1 + 2 * t * (1 - t) * cx + t * t * x2;
        let y = (1 - t) * (1 - t) * y1 + 2 * t * (1 - t) * cy + t * t * y2;
        return [x, y];
    }

    this.getBezierPoints = function (num, p1, p2, p3, p4) {
        let func = null;
        const points = [];
        // console.log("p1 = ", p1);
        // console.log("p2 = ", p2);
        // console.log("p3 = ", p3);
        // console.log("p4 = ", p4);

        if (!p3 && !p4) {
            func = this.oneBezier;
        } else if (p3 && !p4) {
            func = this.twoBezier;
        } else if (p3 && p4) {
            func = this.threeBezier;
        }
    
        for (let i = 0; i < num; i++) {
            points.push(func(i / num, p1, p2, p3, p4));
        }

        if (p4) {
            points.push(p4);
        } else if (p3) {
            points.push(p3);
        }
      
        return points;
    }
}



/**
 * 
 */
var DouTool = function (bezierObj) {

    // 贝塞尔曲线生成器
    this.bezier = null;
    if (bezierObj) {
        this.bezier = bezierObj;
    }
    
     // 控制总得点位数量
     this.dotNumber = 1200;

     // 控制滑动速度, 单位: ms
     this.speed = random(600, 900);
 
     // 控制变速的坐标偏移量
     this.offset = 150;
 
    
     this.pool = {
         'popThread': null,
     };

    this.consoleStatus = false;

    this.log = function (msg) {
        // if (!this.consoleStatus) {
        //     console.show();
        //     this.consoleStatus = true;
        // }
        // console.info(msg);
        toast(msg);
    }

    this.up = function () { 
        const p1 = [this.random(400, 900), this.random(100, 300)]; // x: [550, 900], y: [400, 900]
        const p2 = [this.random(550, 900), this.random(1300, 1680)]; // x: [300, 700], y: [1300, 1600]
        // const c1 = [this.random(500, 600), this.random(600, 1200)]; // x: [500, 600], y: [600, 1200]
        const c1 = [450, 1000]; 

        // console.log("p1", p1);
        // console.log("p2", p2);
        // console.log("c1", c1);

        // console.log("\n\n");

        const point_list = [];

        this.bezier.getBezierPoints(this.dotNumber, p1, c1, p2).forEach(function (v, k) {
            let d = v.map(function (e, i) {
                return parseInt(e, 10);
            })
            
            // console.log("\n\n")
            // console.log(k, d);

            point_list.unshift(d);
        
        });

        // console.log("point_list", point_list);
        point_list.unshift(this.random(600, 900));
        gesture.apply(null, point_list);
    }

    this.down = function () {
        setInterval(function () {
            console.log("test");
        }, 1000);
    }

    this.random = function (min, max) {
        return Math.floor(Math.random() * (max - min) ) + min;
    }

    this.clearTimer = function () {
        clearInterval(this.down());
    }

    // 检测是否是推荐内容
    this.checkIsRecommend = function () {
        let ads = descContains("查看详情").exists();
        if (ads) {
            toastLog("跳过推荐的广告");
            sleep(this.random(1000, 2000));
            return true;
        }
        let rec = textContains("不感兴趣").exists();
        if (rec) {
            toastLog("跳过推荐关注的人");
            sleep(this.random(1000, 2000));
            return true;
        }

        if (textContains("看直播").exists() || textContains("最高领").exists()) {
            toastLog("跳过推荐的直播");
            sleep(this.random(1000, 2000));
            return true;
        }

        return false;
    }

    // 翻评论
    this.seeComment = function () {
        this.log("准备翻看评论");
        sleep(this.random(1000, 2000));

        // 检测是否是推荐内容
        if (this.checkIsRecommend()) {
            return true;
        }

        // commentObj = descContains("评论").depth(26).findOnce(1);
        // if (!commentObj) {
        //     this.log("没有找到评论按钮, 返回");
        //     sleep(this.random(1000, 2000));
        //     return true;
        // }

        // commentObj.click()

        setScreenMetrics(1080, 1920);
        click(980, 1150);
        sleep(this.random(2000, 3000));

        if (textContains("暂无评论").exists()) {
            this.log("没有评论, 返回");
            sleep(this.random(1000, 2000));
            back();
            return true;
        }

        while (true) {
            let cnt = this.random(0, 4);
            for (let i = 0; i <= cnt; i ++ ) {
                this.up();
                sleep(this.random(1000, 2000));
            }
            break;
        }
        this.log("返回继续刷下一条视频");
        sleep(this.random(1000, 2000));
        back();
    }

    // 准备翻看作者主页
    this.seeAllByAvatar = function () {
        let headerObj = id("user_avatar").findOne();
        if (headerObj) {

             // 检测是否是推荐内容
            if (this.checkIsRecommend()) {
                return true;
            }

            this.log("准备翻看作者主页");
            sleep(this.random(1500, 2000));

            // headerObj.click();
            setScreenMetrics(1080, 1920);
            click(1000, 680);


            sleep(this.random(2000, 3000));

            while (true) {
                let cnt = this.random(0, 3);
                for (let i = 0; i <= cnt; i ++ ) {
                    this.up();
                    sleep(this.random(1000, 2000));
                }
                break;
            }
            this.log("返回继续刷下一条视频");
            sleep(this.random(1000, 2000));
            back();
            sleep(this.random(1000, 2000));
        }
        return true;
    }

    // 翻看拍同款
    this.seeMusicCover = function () {
        let headerObj = desc("音乐封面").findOne();
        if (headerObj) {

            // 检测是否是推荐内容
            if (this.checkIsRecommend()) {
                return true;
            }

            this.log("准备翻看拍同款");
            sleep(this.random(1500, 2000));

            // headerObj.click();
            setScreenMetrics(1080, 1920);
            click(980, 1670);

            sleep(this.random(2000, 3000));
            while (true) {
                let cnt = this.random(3, 5);
                for (let i = 0; i <= cnt; i ++ ) {
                    if (i == 1) { // 随机点开1-9中的视频, 翻两下
                        let num = this.random(1, 9);
                        let itemObj = descContains("视频" + num).findOne();
                        if (itemObj) {
                            this.log("随机点开第" + num + "个视频看一下");
                            sleep(this.random(1000, 2000));
                            itemObj.click();
                            sleep(this.random(2000, 3000));
                            
                            this.up();
                            sleep(this.random(2000, 3000));
                            this.up();
                            sleep(this.random(2000, 3000));
                            this.log("返回上一页");
                            sleep(this.random(1000, 2000));
                            back();
                        }
                    }
                    this.up();
                    sleep(this.random(1000, 2000));
                }
                break;
            }
            this.log("返回继续刷下一条视频");
            sleep(this.random(1000, 2000));
            back();
            sleep(this.random(1000, 2000));
        }
    }

    this.watch = function () {
        while (true) {
            // let limit = this.random(3000, 8000);
            let limit = this.random(1000, 3000);

            this.log("等待" + (limit/1000) + "秒后刷下一条视频");
            sleep(limit);

            this.up();

            if (limit % 19 == 0) {
                // 翻看个人主页
                this.seeAllByAvatar();
            }

            if (limit % 7 == 0) {
                 // 翻看拍同款
                 this.seeMusicCover();
            }

            if (limit % 5 == 0) {
                // 翻评论
                this.seeComment()
            }
        }
    }

    this.debug = function () {

        try {
            let thread_a = threads.start(function(){
                //在新线程执行的代码
                let aa = threads.currentThread();
                console.log("aa", aa);
                while(true){
                    log("aa子线程");
                    sleep(3000);
                }
            });
            console.log("thread_a isAlive()", thread_a.isAlive());
            thread_a.interrupt();
            console.log("thread_a isAlive()", thread_a.isAlive());
    
    
            let bb = threads.currentThread();
            console.log("bb", bb);
            while(true){
                sleep(3000);
                log("脚本主线程");
            }

        } catch (e) {
            console.log("e values: ", e);

        }
       
    }

    this.listenShutdown = function () {
        var shutdownThread = threads.start(function () {
            //启用按键监听
            events.observeKey();
            //监听音量上键按下 onceKeyDown(keyName, listener)
            events.onceKeyDown("volume_down", function(event){
                tool.log("刷不动了, 休息一会儿");
                threads.shutDownAll();
                exit();
            });
        });

        shutdownThread.waitFor(); // 等待子线程启动
    }

    // 监听弹窗事件
    this.listenPop = function () {
        var popThread = threads.start(function () {
            while (true) {
                // 检测青少年弹窗
                if (text("青少年模式").exists()) {
                    tool.log("关闭这个弹窗");
                    sleep(tool.random(1000, 2000));
                    text("我知道了").findOne().click();
                }

                if (text("收下我的福利").exists()) {
                    tool.log("关闭这个弹窗");
                    sleep(tool.random(1000, 2000));
                    back();
                }
                sleep(2000);
            }
        });
        popThread.waitFor(); // 等待子线程启动
        tool.pool.popThread = popThread;
    }

    this.openDouYin = function () {
        this.log("准备打开抖音");
        sleep(this.random(1000, 2000));
       
        launchApp("抖音极速版");
        sleep(this.random(5000, 10000));

        return true;

    }
}



ui.startScript.click(function () {
    var toolThread = threads.start(function () {
    
        bezier = new Bezier();
        tool = new DouTool(bezier);
        sleep(tool.random(1000, 2000));
        tool.log("随时按下音量减键停止运行");
        // 监听停止事件
        tool.listenShutdown(); 
        
        tool.log("监听弹窗并自动关闭");
        sleep(tool.random(1000, 2000));
        // 监听弹窗事件
        tool.listenPop();

        sleep(tool.random(1000, 2000));
        // 打开抖音
        tool.openDouYin();

       

        tool.watch();

    });
    toolThread.waitFor(); // 等待子线程启动
});
